<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <h2>个人设置</h2>
        </div>
      </template>

      <el-tabs>
        <el-tab-pane label="壁纸设置">
          <wallpaper-selector />
        </el-tab-pane>
        
        <el-tab-pane label="个人信息">
          <div class="profile-settings">
            <el-form label-position="top" :model="profileForm" :rules="profileRules" ref="profileFormRef">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="profileForm.username" disabled />
              </el-form-item>
              
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="profileForm.nickname" />
              </el-form-item>
              
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="profileForm.email" />
              </el-form-item>
              
              <el-form-item label="头像">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleAvatarChange"
                >
                  <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="updateProfile">保存</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="安全设置">
          <div class="security-settings">
            <el-form label-position="top" :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
              <el-form-item label="当前密码" prop="currentPassword">
                <el-input v-model="passwordForm.currentPassword" type="password" show-password />
              </el-form-item>
              
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="passwordForm.newPassword" type="password" show-password />
              </el-form-item>
              
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="updatePassword">更新密码</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="系统设置">
          <div class="system-settings">
            <h3>界面设置</h3>
            <div class="setting-item">
              <span>主题</span>
              <el-switch
                v-model="darkMode"
                active-text="暗色模式"
                inactive-text="亮色模式"
                @change="toggleTheme"
              />
            </div>
            
            <div class="setting-item">
              <span>字体大小</span>
              <el-slider v-model="fontSize" :min="12" :max="20" @change="changeFontSize" />
            </div>
            
            <h3>本地存储</h3>
            <div class="storage-info">
              <p>应用缓存: {{ formatSize(storageInfo.appCache) }}</p>
              <p>用户数据: {{ formatSize(storageInfo.userData) }}</p>
              <el-button type="danger" @click="clearAppCache">清除缓存</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import WallpaperSelector from '@/components/WallpaperSelector.vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import type { UploadFile } from 'element-plus'

const userStore = useUserStore()

// 表单引用
const profileFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 个人信息表单
const profileForm = reactive({
  username: '',
  nickname: '',
  email: '',
  avatar: ''
})

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = reactive<FormRules>({
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

// 密码验证规则
const passwordRules = reactive<FormRules>({
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
})

// 系统设置
const darkMode = ref(localStorage.getItem('darkMode') === 'true')
const fontSize = ref(parseInt(localStorage.getItem('fontSize') || '14'))
const storageInfo = reactive({
  appCache: 0,
  userData: 0
})

// 初始化数据
onMounted(async () => {
  if (userStore.isLoggedIn) {
    // 加载用户数据
    const user = userStore.userInfo
    if (user) {
      profileForm.username = user.username
      profileForm.nickname = user.nickname || ''
      profileForm.email = user.email || ''
      profileForm.avatar = user.avatar || ''
    }
    
    // 获取存储信息
    calculateStorageUsage()
  }
})

// 更新个人信息
const updateProfile = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // TODO: 调用API更新个人信息
        ElMessage.success('个人信息更新成功')
      } catch (error) {
        console.error('更新个人信息失败', error)
        ElMessage.error('更新个人信息失败')
      }
    }
  })
}

// 更新密码
const updatePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // TODO: 调用API更新密码
        ElMessage.success('密码更新成功')
        
        // 清空表单
        passwordForm.currentPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
      } catch (error) {
        console.error('更新密码失败', error)
        ElMessage.error('更新密码失败')
      }
    }
  })
}

// 处理头像上传
const handleAvatarChange = (file: UploadFile) => {
  // TODO: 上传头像
  const reader = new FileReader()
  reader.onload = (e) => {
    profileForm.avatar = e.target?.result as string
  }
  reader.readAsDataURL(file.raw!)
}

// 切换主题
const toggleTheme = (value: boolean) => {
  localStorage.setItem('darkMode', value.toString())
  // TODO: 实现主题切换逻辑
}

// 修改字体大小
const changeFontSize = (value: number) => {
  localStorage.setItem('fontSize', value.toString())
  document.documentElement.style.fontSize = `${value}px`
}

// 计算存储使用情况
const calculateStorageUsage = () => {
  // 模拟计算存储使用
  const estimateStorage = () => {
    let total = 0
    for (const key in localStorage) {
      if (localStorage.hasOwnProperty(key)) {
        total += (localStorage[key].length * 2) / 1024
      }
    }
    return total
  }
  
  storageInfo.appCache = estimateStorage() * 0.7
  storageInfo.userData = estimateStorage() * 0.3
}

// 格式化存储大小
const formatSize = (kb: number) => {
  if (kb < 1024) {
    return `${kb.toFixed(2)} KB`
  } else {
    return `${(kb / 1024).toFixed(2)} MB`
  }
}

// 清除应用缓存
const clearAppCache = () => {
  // 清除部分localStorage
  const keysToPreserve = ['token', 'currentWallpaper', 'darkMode', 'fontSize']
  for (const key in localStorage) {
    if (localStorage.hasOwnProperty(key) && !keysToPreserve.includes(key)) {
      localStorage.removeItem(key)
    }
  }
  
  // 更新存储使用情况
  calculateStorageUsage()
  
  ElMessage.success('缓存已清除')
}
</script>

<style scoped>
.settings-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-settings,
.security-settings,
.system-settings {
  padding: 20px 0;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.storage-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  margin-top: 10px;
}

.avatar-uploader {
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}

h3 {
  margin-top: 30px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
</style> 